import React, { PureComponent } from 'react';
import '@ant-design/compatible/assets/index.css';
import { connect } from 'dva';
import { Badge, Card, message, Table, Row, Col, Button, Popconfirm } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { filterAuth } from '@/support/common';
import moment from 'moment';
import PateoTable from '../../../components/common/PateoTable';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import styles from '../../../components/common/PateoTable/TableList.less';
import Ellipsis from '../../../components/Ellipsis';
import RuleModal from '../commonModal/ruleModal';
import MaskText from '@/components/MaskText';

const mapStateToProps = (state: any) => ({
  vehicleAlarmRule: state.vehicleAlarmRule,
  loading: state.loading.models['vehicleAlarmRule'],
  permissions: state?.menu?.permissions,
  user: state?.menu?.userProfile,
});

class VehicleAlarmRule extends PureComponent<any, any> {
  //  operator: user?.accountName
  constructor(props: any) {
    super(props);
    this.state = {
      ruleModalVisible: false,
      ruleData: {},
      ruleModalType: 'add',
      alarmTypeData: [
        {
          value: 0,
          label: '弱提醒',
        },
        {
          value: 1,
          label: '弹框提醒',
        },
        {
          value: 2,
          label: '霸屏提醒',
        },
      ],
      formValues: {},
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const tempParam = {
      ...formValues,
      pageNo: 1,
      pageSize: 10,
      // tenantCode: 'MATC',
    };
    dispatch({
      type: 'vehicleAlarmRule/postFetchPageParamAndBody', // postFetchPage
      payload: { url: '/commodity/vehicle/warnRule/page', ...tempParam },
    });
  }

  handleFormReset = () => {
    this.setState({
      formValues: {},
    });
  };

  handleAdd = (record: any) => {
    this.setState({
      ruleModalVisible: true,
      ruleModalType: 'add',
    });
  };

  closeRuleModal = () => {
    this.setState({
      ruleModalVisible: false,
      ruleData: {},
      ruleModalType: 'add',
    });
  };

  handleEnable = (record: any, enable: any) => {
    //  enable: 0 启用；1 停用
    const { dispatch, user } = this.props;
    dispatch({
      type: 'vehicleAlarmRule/postDataWithRes',
      payload: {
        url: '/commodity/vehicle/warnRule/enable',
        sid: record?.sid,
        warnRuleEnable: enable,
        operator: user?.accountName,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          message.success('操作成功');
        } else {
          // message.error(res.statusMessage);
        }
        this.handleRefresh();
      },
    });
  };

  handleEdit = (record: any) => {
    //  编辑
    this.setState({
      ruleModalVisible: true,
      ruleData: record,
      ruleModalType: 'edit',
    });
  };

  handleDel = (record: any) => {
    //  删除
    const { dispatch, user } = this.props;
    dispatch({
      type: 'vehicleAlarmRule/postDataWithRes',
      payload: {
        url: '/commodity/vehicle/warnRule/delete',
        sid: record?.sid,
        operator: user?.accountName,
      },
      callback: (res: any) => {
        // 删除成功
        if (res.statusCode === '0') {
          message.success('删除成功');
        } else {
          message.error(res.statusMessage);
        }
        this.handleRefresh();
      },
    });
  };

  handleRefresh = () => {
    const { dispatch } = this.props;
    this.handleFormReset();
    const tempParam = {
      page: 1,
      size: 10,
    };
    dispatch({
      type: 'vehicleAlarmRule/postFetchPageParamAndBody',
      payload: { url: '/commodity/vehicle/warnRule/page', ...tempParam },
    });
  };

  render() {
    const {
      vehicleAlarmRule: {
        pageData: { rows, pagination, total },
      },
      loading,
      permissions,
      dispatch,
      location: { pathname = '/' },
    } = this.props;
    // let pathname = '/commercialVehicleMonitor/vehicleAlarmRule'
    const { formValues, alarmTypeData, ruleModalType, ruleData, ruleModalVisible } = this.state;

    const columns = [
      {
        title: '告警规则名称',
        dataIndex: 'warnRuleName',
      },
      {
        title: '使用场景',
        dataIndex: 'userCase',
        render: (text: any) => (text == 0 ? '其他' : '锁车'),
      },
      {
        title: '标题',
        dataIndex: 'warnTitle',
      },
      {
        title: '告警显示方式',
        dataIndex: 'warnShowType',
        render: (text: any) => {
          let tempStr = '';
          alarmTypeData.some((v: any) => {
            const state = v.value == text;
            if (state) {
              tempStr = v.label;
            }
            return state;
          });
          return tempStr;
        },
      },
      {
        title: '告警内容',
        dataIndex: 'warnContent',
        render: (text: any) => {
          return (
            <Ellipsis length={20} tooltip>
              {text}
            </Ellipsis>
          );
        },
      },
      {
        title: '是否开启TTS语音播报',
        dataIndex: 'ttsEnable',
        render: (text: any) => (text == 0 ? '开启' : '不开启'),
      },
      {
        title: 'TTS语音播报内容',
        dataIndex: 'ttsContent',
        render: (text: any) => {
          return (
            <Ellipsis length={20} tooltip>
              {text}
            </Ellipsis>
          );
        },
      },
      {
        title: '生效状态',
        dataIndex: 'ruleStatus',
        render: (text: any) => (text == 0 ? '未生效' : text == 1 ? '已生效' : '已停用'),
      },
      {
        title: '创建人',
        dataIndex: 'createBy',
        render(val: any) {
          return <MaskText text={val} type="name" />;
        },
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        // render: (text: any) => moment(text).format('YYYY-MM-DD HH:mm:ss')
      },
      {
        title: '操作',
        dataIndex: 'opt',
        width: 240,
        fixed: 'right',
        render: (text: any, record: any) => {
          // ruleStatus：0 未生效、1 已生效、2 已停用
          // 0：删除、修改、启用; 1：修改、停用; 2：修改、启用
          const btns = [
            {
              title: '启用',
              key: 'enable',
              auth: 'rule_doEnable',
              message: '确认要启用吗？',
              Popconfirm: true,
              hide: record.ruleStatus === 1,
              onConfirm: () => {
                this.handleEnable(record, 0);
              },
            },
            {
              title: '停用',
              key: 'disable',
              auth: 'rule_doDisable',
              message: '确认要停用吗？',
              Popconfirm: true,
              hide: record.ruleStatus !== 1,
              onConfirm: () => {
                this.handleEnable(record, 1);
              },
            },
            {
              title: '修改',
              key: 'edit',
              auth: 'rule_doEdit',
              message: '该告警规则可能已经被使用，确认要修改吗？',
              Popconfirm: true,
              onConfirm: () => {
                this.handleEdit(record);
              },
            },
            {
              title: '删除',
              key: 'del',
              auth: 'rule_doDel',
              message: '确认要删除吗？',
              Popconfirm: true,
              hide: record.ruleStatus !== 0,
              onConfirm: () => {
                this.handleDel(record);
              },
            },
          ];
          return <PateoAuthButtons btns={btns} max={3} pathname={pathname} />;
        },
      },
    ];

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      total,
      showTotal: () => (
        <span>共&nbsp;{total}&nbsp;条</span>
        // <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };

    const tableProps = {
      columns,
      rowKey: (record: any) => record.sid,
      dataSource: rows,
      loading,
      pagination: paginationProps,
      scroll: { x: 'max-content' },
    };

    const searchItems = [
      {
        title: '告警规则名称',
        type: 'input',
        // customStyle: 6,
        key: 'warnRuleName',
      },
      {
        title: '告警显示方式',
        type: 'select',
        // customStyle: 6,
        selectOptions: alarmTypeData,
        key: 'warnShowType',
      },
      {
        title: '是否开启TTS语音播报',
        type: 'select',
        // customStyle: 6,
        selectOptions: [
          { value: '0', label: '开启' },
          { value: '1', label: '不开启' },
        ],
        key: 'ttsEnable',
      },
      {
        title: '生效状态',
        type: 'select',
        // customStyle: 6,
        selectOptions: [
          { value: '0', label: '未生效' },
          { value: '1', label: '已生效' },
          { value: '2', label: '已停用' },
        ],
        key: 'ruleStatus',
      },
      {
        title: '创建人',
        type: 'input',
        // customStyle: 6,
        key: 'createBy',
      },
    ];

    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{
              type: 'vehicleAlarmRule/postFetchPageParamAndBody',
              url: '/commodity/vehicle/warnRule/page',
            }}
            extraArgs={{ pageNo: 1, pageSize: 10 }}
            saveFormValues={(val: any) =>
              this.setState({
                formValues: Object.assign(formValues, val),
              })
            }
            handleFormReset={this.handleFormReset}
          />
        </Card>
        <Card className={styles.standardTable}>
          <Row>
            <Col span={12}>
              {filterAuth('rule_doAdd', permissions, pathname) ? (
                <div className="my_newItem">
                  <Button
                    size="small"
                    icon={<PlusOutlined />}
                    type="primary"
                    onClick={() => this.handleAdd()}
                  >
                    新建规则
                  </Button>
                </div>
              ) : null}
              {/* <Button
                size="small"
                icon={<PlusOutlined />}
                type="primary"
                onClick={() => this.handleAdd()}
              >
                新建规则
              </Button> */}
            </Col>
          </Row>
          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{
              type: 'vehicleAlarmRule/postFetchPageParamAndBody',
              url: '/commodity/vehicle/warnRule/page',
              extraArgs: {},
            }}
            formValues={formValues}
            currentName="pageNo"
            pageSizeName="pageSize"
          />
          <RuleModal
            onRef={(val: any) => (this.ruleModal = val)}
            data={ruleData}
            type={ruleModalType}
            modalVisible={ruleModalVisible}
            refreshPage={this.handleRefresh}
            closeModal={this.closeRuleModal}
          />
        </Card>
      </div>
    );
  }
}
export default connect(mapStateToProps)(VehicleAlarmRule);
